package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author rookie001
 * @creat 2023-06-18-15:25
 */
@Component
@Slf4j
public class SyncArticleListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    //监听消息
    @KafkaListener(topics = ArticleConstants.HOT_ARTICLE_FIRST_PAGE)
    public void listenHotArticle(String message) {
        if (StringUtils.isNotEmpty(message)) {
            log.info("message {}", message);
            SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
            if (searchArticleVo!= null) {
                IndexRequest indexRequest=new IndexRequest("app_info_article");
                indexRequest.id(searchArticleVo.getId().toString());
                indexRequest.source(JSON.toJSONString(searchArticleVo), XContentType.JSON);
                try {
                    // index方法 保存到es中
                    restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
